const query = require('../config/db');
var express = require('express');
var router = express.Router();

// 搜索的接口 第2页的关于’数学‘的3条数据
// 请求参数：传递关键词 kw（数学） page(页码) size(一页的条数)
// 响应数据：总条数、总页数、页码(1)、数据
router.get("/s", async (req, res, next) => {
    //取出前端传递的数据
    let { kw = '', page = 1, size = 10 } = req.query;
    //前端传递过来有可能是字符串，强制转为number
    page=Number(page)
    size=Number(size)

    //判断关键词不能为空
    if (kw === '') {
        next("请输入关键词");
        return;
    }

    //有关键词
    //查询了和关键词相关的所有数据
    let sql1 = `SELECT * FROM e_course WHERE title like '%${kw}%' OR area_name LIKE '%${kw}%' OR grade_name LIKE '%${kw}%' OR subject_name LIKE '%${kw}%' or
  category_name LIKE '%${kw}%'`;
    let result1 = await query(sql1)//所有的数据

    //总条数 32
    let totalNum = result1.length;

    //总页数 Math.ceil(32/10)
    let totalPage = Math.ceil(totalNum / size)

    //页码 page

    //数据
    let sql2 = `SELECT * FROM e_course WHERE title like '%${kw}%' OR area_name LIKE '%${kw}%' OR grade_name LIKE '%${kw}%' OR subject_name LIKE '%${kw}%' or
    category_name LIKE '%${kw}%' limit ${(page - 1) * size},${size}`;
    let result2 = await query(sql2)

    // 返回给前端
    res.send({
        succcess: true,
        msg: "查询成功",
        status: 200,
        data: {
            //总条数
            totalNum,
            //总页数
            totalPage,
            //当前页码
            page,
            //数据
            list: result2
        }
    })
})

module.exports = router;
